// 物资
import Util from '@/gis/Util';
import { PanLogic } from '../PanLogic'

const componentBase = (G as any).base.ComponentBase;
const component = componentBase.extend({
    // 属性
    options: {
        map: null,
        simpleRenderMgr: null,
        popupManager: null,
        featureLocate: null,
        featureHighlight: null,
        symbolConfig: null,
        highLightId: 'material_sjts', // 高亮id
        popupId: 'popup_material_sjts', // 弹窗唯一标识
        popupIds: [], // 记录所有的弹出框id
        showLevel: 18,
        statisticsTooltipShowByLevel: false, //  弹出框随地图层级变化是否显示，默认
        popupEventName: 'popup', // 详情框事件名
        mousePopupEventName: 'mouse_popup', // 点击/悬浮弹框事件名
        materialTypesEventName: 'materialTypes', // 物资类别事件名
        featureType: 'material_sjts', // 图层标识
        server: null, // GIS服务，提供types和find两个接口
    },
    // 初始化
    initialize(options: any) {
        componentBase.prototype.initialize.call(this, options);

        this.symbolSet = {  // 存储所有的图标符号
            0: {   // 供应点图标符号
                type: 'PictureMarkerSymbol',
                options: {
                    width: 34,
                    height: 46,
                    offsetX: 17,
                    offsetY: 46,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons.material_0_icon,
                }
            },
            1: {  // // 需求点图标符号
                type: 'PictureMarkerSymbol',
                options: {
                    width: 34,
                    height: 46,
                    offsetX: 17,
                    offsetY: 46,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons.material_1_icon,
                }
            },
        };
        this.updateSymbolSet = {  // 存储所有的高亮图标符号
            0: {   // 供应点高亮图标符号
                type: 'PictureMarkerSymbol',
                options: {
                    width: 56,
                    height: 63,
                    offsetX: 28,
                    offsetY: 63,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons.material_0_hover_icon,
                }
            },
            1: {  // 需求点高亮图标符号
                type: 'PictureMarkerSymbol',
                options: {
                    width: 56,
                    height: 63,
                    offsetX: 28,
                    offsetY: 63,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons.material_1_hover_icon,
                }
            },
        };
        /**
         * serviceType:供需类型，0-供应点，1-需求点
         * materialType：物资类型，1-防护，2-消杀，3-医疗设备，4-治疗药品，5-其他
         */
        this.getSymbol = (serviceType: any, materialType: any) => {
            let symbolType = 5;
            switch (materialType * 1) {
                case 1:
                    symbolType = 1;
                    break;
                case 2:
                    symbolType = 2;
                    break;
                case 3:
                    symbolType = 3;
                    break;
                case 4:
                    symbolType = 4;
                    break;
                default:
                    symbolType = 5;
                    break;
            }
            return {   // 供应点图标符号
                type: 'PictureMarkerSymbol',
                options: {
                    width: 34,
                    height: 46,
                    offsetX: 17,
                    offsetY: 46,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons[`material_${serviceType}_${symbolType}_icon`],
                }
            }
        };
        /**
         * serviceType:供需类型，0-供应点，1-需求点
         * materialType：物资类型，1~4-1-防护，5~7-2-消杀，8~10-3-医疗设备，11~12-4-治疗药品，13-5-其他
         */
        this.getUpdateSymbol = (serviceType: any, materialType: any) => {
            let symbolType = 5;
            switch (materialType * 1) {
                case 1:
                    symbolType = 1;
                    break;
                case 2:
                    symbolType = 2;
                    break;
                case 3:
                    symbolType = 3;
                    break;
                case 4:
                    symbolType = 4;
                    break;
                default:
                    symbolType = 5;
                    break;
            }
            return {   // 供应点高亮图标符号
                type: 'PictureMarkerSymbol',
                options: {
                    width: 56,
                    height: 63,
                    offsetX: 28,
                    offsetY: 63,
                    opacity: 1,
                    rotation: 0,
                    source: this.options.symbolConfig.icons[`material_${serviceType}_${symbolType}_hover_icon`],
                }
            }
        }
        this.panLogic = new PanLogic(options)
    },
    //  销毁
    destroy() {
        componentBase.prototype.destroy.call(this);
    },

    load(list: any) {
        componentBase.prototype.load.call(this);
        // 图层事件监听，此处开启的是地图Map的事件监听
        this.options.simpleRenderMgr.on('mouseover', this._onLayerClick, this);
        this._addPointToMap(list);

        // 添加 物资弹出框
        this._addStatisticsTooltips(list);

        // 调整地图视野范围
        this._fit();
    },
    addListeners() {
        // 添加事件监听，load调用时父类触发
    },

    unload() {
        componentBase.prototype.unload.call(this);
        // 关闭图层事件监听，此处关闭的是地图Map的事件监听
        this.options.simpleRenderMgr.off('mouseover', this._onLayerClick, this);
        // 删除弹出框和高亮，删除图层
        this._removePointLayer();

        // 删除物资信息的弹出框--初始显示的统计信息弹出框，非单击弹出的详情框
        this._removeStatisticsTooltips();

        // 取消 物资信息的弹出框 随地图层级变化的监听事件
        this.map.un("resolutionchanged", this._listenerByLevel);

        this.options.statisticsTooltipShowByLevel = false;

        // 删除树状图的定位点
        this.panLogic.removePosition();
    },

    removeListeners() {
        // 移除事件监听，unload调用时父类触发
    },
    // 关闭弹出框
    closePopup() {
        this.options.popupManager.remove(this.options.popupId);
    },
    // 定位点
    fitPointLocation(x: any, y: any) {
        const geom = {
            type: 'Point',
            coordinates: [parseFloat(x), parseFloat(y)],
        };
        const pointdata: any = {
            type: 'geojson',
            geom,
        };
        this.options.featureLocate.fit(pointdata, {
            maxZoom: this.map.getZoomLevel(),
        });
    },
    // 删除点图层
    _removePointLayer() {
        // 删除点高亮和详情框
        this.closePopup();
        // 同时删除供应和需求图层
        this.options.simpleRenderMgr.remove(this.options.featureType);
    },
    // 图层点击事件处理
    _onLayerClick(features: any) {
        this.closePopup();
        let pointFeature: any = null;
        const list = features.list;
        for (const item of list) {
            // 识别需求|供应点数据
            if (item && item.featureType === this.options.featureType) {
                pointFeature = item;
                break;
            }
        }
        // 优先实现需求|供应点的点击识别事件
        if (pointFeature) {   // 实现需求|供应点的点击识别事件
            const featureObj: any = pointFeature;
            const attributeObj: any = Util.attributeSet2Object(featureObj.element.attributeSet);
            const element = featureObj.element;
            const type = attributeObj.needMaterialType;
            const materialType = attributeObj.classtype;
            // 点闪烁
            this._showHighLight([element.geometry.x, element.geometry.y], type, materialType);
            // 添加点识别弹出框
            this._clickTip(element);
            // 定位点
            // this.fitPointLocation(element.geometry.x, element.geometry.y);
        }
    },
    /**
     * 将物资需求|供应点添加到地图上
     * @param pointArr 数据信息，包含坐标信息
     */
    _addPointToMap(pointArr: any) {
        // 添加点数据
        const self = this;
        const simpleRenOpt: any = {
            featureType: this.options.featureType,
            featureName: '物资需求分布',
            list: pointArr,
            type: 0, // 使用elementLayer,
            idField: 'materialId', // 数据唯一标识的属性
        };
        simpleRenOpt.geometryBuilder = new this.options.PointGeometryBuilder({
            geometryField: ['longitude', 'latitude'],
        });

        const SymbolBuilder = (G as any).utils.SymbolBuilder.extend({
            build: (builddata: any) => {
                // 根据数据属性控制不同的显示效果
                const serviceType = builddata.needMaterialType;
                const materialType = builddata.classtype;
                const markerSymbol = G.utils.RenderUtil.object2Symbol(self.getSymbol(serviceType, materialType));
                return markerSymbol;
            },
        });
        simpleRenOpt.symbolBuilder = new SymbolBuilder();
        this.options.simpleRenderMgr.add(simpleRenOpt);
    },
    // 隐藏高亮
    _hideHighlight() {
        this.options.featureHighlight.removeHighlight(this.options.highLightId);
    },
    // 设置弹出框样式
    _setTooltipStyle(eleId: any, dataObj: any) {
        if (dataObj.needMaterialType === '1') {

            if (dataObj.unitName) {
                jQuery(eleId).append('<div class="GisPopup_hospital">' +
                    '<div class="position">' +
                    '<div class="name" title=' + dataObj.managerUnit + '>' + dataObj.managerUnit + '</div>' +
                    '<div class="num_hospital" title=' + dataObj.number + '>' + dataObj.number + '</div>' +
                    '<div class="unitName" title=' + dataObj.unitName + '>' + dataObj.unitName + '</div>' +
                    '</div>' +
                    '</div>');
            } else {
                jQuery(eleId).append('<div class="GisPopup_hospital">' +
                    '<div class="position">' +
                    '<div class="name" title=' + dataObj.managerUnit + '>' + dataObj.managerUnit + '</div>' +
                    '<div class="num_hospital" title=' + dataObj.number + '>' + dataObj.number + '</div>' +
                    '<div class="unitName" title="空">空</div>' +
                    '</div>' +
                    '</div>');
            }

        } else if (dataObj.needMaterialType === '0') {

            if (dataObj.unitName) {
                jQuery(eleId).append('<div class="GisPopup_unit">' +
                    '<div class="position">' +
                    '<div class="name" title=' + dataObj.managerUnit + '>' + dataObj.managerUnit + '</div>' +
                    '<div class="num_unit" title=' + dataObj.number + '>' + dataObj.number + '</div>' +
                    '<div class="unitName" title=' + dataObj.unitName + '>' + dataObj.unitName + '</div>' +
                    '</div>' +
                    '</div>');
            } else {
                jQuery(eleId).append('<div class="GisPopup_unit">' +
                    '<div class="position">' +
                    '<div class="name" title=' + dataObj.managerUnit + '>' + dataObj.managerUnit + '</div>' +
                    '<div class="num_unit" title=' + dataObj.number + '>' + dataObj.number + '</div>' +
                    '<div class="unitName" title="空">空</div>' +
                    '</div>' +
                    '</div>');
            }


        }
    },
    // 点动画闪烁
    _showHighLight(coordinate: number[], type: any, materialType: any) {
        this._hideHighlight();
        const symbolObj: any = this.getUpdateSymbol(type, materialType);
        const options = {
            data: {
                type: 'wkt',
                geom: 'POINT(' + coordinate[0] + ' ' + coordinate[1] + ')',
            },
            style: symbolObj,
        };
        this.options.featureHighlight.addHighlight(this.options.highLightId, options);
    },
    // 弹出对话框
    _clickTip(element: any) {
        const point: any = element.geometry.getBaryCenter();
        const self = this;
        const dataObj: any = Util.attributeSet2Object(element.attributeSet);
        this.options.popupManager.addSimple({
            id: this.options.popupId,
            anchor: [point.x, point.y],
            className: this.options.popupId,
        });
        const eleId = "#" + self.options.popupId;
        this._setTooltipStyle(eleId, dataObj);
    },

    // 添加 物资信息的统计弹框，并绑定统计弹框随地图层级变化的显隐事件
    _addStatisticsTooltips(pointArr: any) {
        const olMap = this.map.map;
        if (olMap) {
            const view = olMap.getView();
            const level = view.getZoom();
            // 保证 地图分辨率不变化也能显示tooltip
            this._showStatisticsTooltips(pointArr, level);
        }
        this._listenerByLevel = this._toggleStatisticsTooltip.bind(this, pointArr);
        this.map.on("resolutionchanged", this._listenerByLevel);
    },


    // 在地图上添加并显示统计弹框
    _showStatisticsTooltips(pointArr: any, level: number) {
        const self = this;
        // 关闭悬浮弹出框
        this.closePopup();
        if (level >= self.options.showLevel) {
            self.options.popupIds.length = 0;
            for (let i = 0, length = pointArr.length; i < length; i++) {
                const item = pointArr[i];
                const lat = item.latitude;
                const lng = item.longitude;
                const anchor = [lng, lat];
                const id = self.options.popupId + "_" + item.materialId;

                self.options.popupIds.push(id);

                self.options.popupManager.addSimple({
                    id,
                    anchor,
                    className: self.options.popupId,
                    autoPan: false,
                });
                const eleId = "#" + self.options.popupId + "_" + item.materialId;
                this._setTooltipStyle(eleId, item);
            }
        }

    },


    // 显隐 tooltip 信息框
    _toggleStatisticsTooltip(pointArr: any, newResolution: any, oldResolution: any, level: number) {
        const self = this;
        level = Math.round(level);
        if (level >= self.options.showLevel && !self.options.statisticsTooltipShowByLevel) {
            // 关闭事件监听
            this.options.simpleRenderMgr.off('mouseover', this._onLayerClick, this);
            self._removeStatisticsTooltips();
            self._showStatisticsTooltips(pointArr, level);
            self.options.statisticsTooltipShowByLevel = true;
        } else if (level < self.options.showLevel && self.options.statisticsTooltipShowByLevel) {
            self.options.statisticsTooltipShowByLevel = false;
            self._removeStatisticsTooltips();
            // 开启事件监听
            this.options.simpleRenderMgr.on('mouseover', this._onLayerClick, this);
        }
    },


    // 删除物资信息的弹出框--初始显示的统计信息弹出框，非单击弹出的详情框
    _removeStatisticsTooltips() {
        const popupIds = this.options.popupIds;
        for (const popId of popupIds) {
            this.options.popupManager.remove(popId);
        }
        this.options.popupIds.length = 0;
    },

    // 调整视野
    _fit() {
        const layer: any = this.options.simpleRenderMgr.getLayer(this.options.featureType);
        const extent: any = G.utils.LayerUtil.getLayerExtent(layer);
        if (extent) {
            this.map.pan(extent, new Array(4).fill(200));
        }
    },

    /**
     * 根据行政区划等级和中心点改变地图视野
     * @param level 要查询的行政区划等级
     * @param center 选中行政区划的中心点,例：[116,39]
     */
    panTo(level: any, center: any) {
        const zoomLevelMap = this.options.symbolConfig.zoom_level_map;
        const zoom = Object.keys(zoomLevelMap).find((item: any) => zoomLevelMap[item] === level * 1);
        this.map.zoomTo(zoom);

        if (center) {
            if (typeof (center) === 'object') {
                center = [center.lng, center.lat];
            }
            const geo = new g2.sfs.Point({ x: center[0] * 1, y: center[1] * 1 });
            const pos = level === "4" ? center : null
            this.panLogic.setPosition(pos)
            this.map.setCenter(geo);
        }
    },

    setCenter(center: any) {
        if (center) {
            const geo = new g2.sfs.Point({ x: center[0] * 1, y: center[1] * 1 });
            this.map.setCenter(geo);
        }
    }
});

export default component;

































